import json

from mg_app_framework import MesCode, send_mes, get_logger
from mg_app_framework.message import make_mes
from tornado.websocket import WebSocketHandler

from .encoder import DefaultEncoder


class BaseWebsocketHandler(WebSocketHandler):
    def data_received(self, chunk):
        pass

    def get_remote_ip(self):
        return self.request.headers.get("X-Real-IP") or \
               self.request.headers.get("X-Forwarded-For") or \
               self.request.remote_ip

    def check_origin(self, origin: str) -> bool:
        return True

    def on_message(self, message):
        pass

    async def send_message(self, message: dict, type_: str, info='', code=MesCode.success):
        return await send_mes(self, type_, message, info, code)

    @classmethod
    async def send_mes(cls, handler, mes_type, data, info='', code=MesCode.success):
        try:
            message = make_mes(mes_type, data, info, code)
            await handler.write_message(json.dumps(message, ensure_ascii=False, cls=DefaultEncoder))
        except Exception as e:
            get_logger().error('sending websocket message failed')
            raise e

    def __copy__(self):
        return self
